<template>
  <div>
    <!-- 切换选项 -->
    <el-radio-group
        style="margin-left: 42%; margin-top: 2vh; margin-bottom: 1vh"
        v-model="viewType"
        @change="handleViewChange"
    >
      <el-radio-button label="approved">通过需求</el-radio-button>
      <el-radio-button label="rejected">驳回需求</el-radio-button>
    </el-radio-group>

    <div class="gva-table-box">
      <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          tooltip-effect="dark"
          @row-click="handleRowClick"
          row-key="ID"
      >
        <el-table-column type="selection" width="50" />

        <el-table-column align="left" label="需求发布日期" width="120">
          <template #default="scope">
            <span>{{ formatDate(scope.row.CreatedAt) }}</span>
          </template>
        </el-table-column>

        <el-table-column align="left" label="订单ID" prop="ID" width="80" />

        <el-table-column
            align="left"
            label="订单Title"
            prop="title"
            width="120"
        />

        <el-table-column align="left" label="价格" width="120">
          <template #default="scope">
            <div>{{ scope.row.budgetMin }} ~ {{ scope.row.budgetMax }} 元</div>
          </template>
        </el-table-column>

        <el-table-column align="left" label="电话" prop="phone" width="180" />

        <el-table-column
            align="left"
            label="需求发布人"
            prop="nickname"
            width="180"
        />

        <el-table-column
            align="left"
            label="订单状态"
            prop="status"
            width="120"
        >
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.status)">
              {{ getTagLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 驳回意见列 -->
        <el-table-column
            v-if="viewType === 'rejected'"
            align="left"
            label="驳回意见"
            prop="backContent"
            width="300"
        >
          <template #default="scope">
            <div>{{ scope.row.backContent }}</div>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column align="center" label="操作" min-width="200">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                  v-show="viewType === 'approved'"
                  type="danger"
                  link
                  @click="
                  (event) => {
                    event.stopPropagation();
                    openRejectDialog(scope.row);
                  }
                "
              >驳回需求</el-button
              >

              <el-button
                  v-show="viewType === 'rejected'"
                  type="primary"
                  link
                  @click="
                  (event) => {
                    event.stopPropagation();
                    editRejectReason(scope.row);
                  }
                "
              >编辑驳回理由</el-button
              >

              <el-button
                  v-show="viewType === 'rejected'"
                  type="primary"
                  link
                  @click="
                  (event) => {
                    event.stopPropagation();
                    approveOrder(scope.row);
                  }
                "
              >通过审核</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 驳回需求弹窗 -->
    <el-dialog title="驳回需求" v-model="rejectDialogVisible" width="30%">
      <el-form :model="rejectForm" label-width="120px">
        <el-form-item label="驳回理由">
          <el-input
              v-model="rejectForm.rejectReason"
              type="textarea"
              rows="4"
              placeholder="请输入驳回理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeRejectDialog">取消</el-button>
        <el-button type="primary" @click="submitReject">确认修改</el-button>
      </template>
    </el-dialog>

    <el-drawer
        v-model="drawerFormVisible"
        :before-close="closeDrawer"
        :show-close="false"
        size="30%"
        direction="rtl"
    >
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">订单处理选项</span>
          <el-button icon="close" @click="closeDrawer" circle></el-button>
        </div>
      </template>

      <el-form :inline="true" :model="form" label-width="120px">
        <!-- 单选按钮选择接单类型：外部接单、内部接单、返回需求 -->
        <el-form-item label="选择操作">
          <el-radio-group v-model="form.orderType">
            <el-radio label="external">外部接单</el-radio>
            <el-radio label="internal">内部接单</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 内部接单时显示额外的表单字段 -->
        <div v-if="form.orderType === 'internal'">
          <el-form-item label="技术方">
            <el-input
                v-model="form.technical"
                autocomplete="off"
                clearable
                placeholder="请输入技术方"
                :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="价格">
            <el-input
              v-model="form.price"
              autocomplete="off"
              clearable
              placeholder="请输入价格,价格必须为整数"
              :style="{ width: '100%' }"
            />
          </el-form-item>
        </div>
      </el-form>

      <div class="flex justify-end mt-4">
        <el-button @click="closeDrawer" size="small">取 消</el-button>
        <el-button type="primary" @click="enterDrawer('submit')" size="small">
          提 交
        </el-button>
      </div>
    </el-drawer>
    <!-- 使用 el-dialog 作为模态框 -->
    <el-dialog
        v-model="dialogFormVisible"
        width="50%"
        :before-close="closeDialog"
    >
      <template #title>
        <div>订单详情</div>
      </template>

      <!-- 子组件 OrderDetail 传递 orderId -->
      <OrderDetail v-if="dialogFormVisible" :orderId="currentOrderId" />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import OrderDetail from "@/components/OrderDetails.vue";

import { formatDate } from "@/utils/format";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  backRequirement,
  editRequirement,
  getRequirementList,
} from "@/api/requirement";

const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const viewType = ref("approved"); // 默认展示通过需求
const rejectDialogVisible = ref(false); // 控制驳回弹窗显示与隐藏
const drawerFormVisible = ref(false);
const rejectForm = ref({
  ID: "", // 当前订单ID
  rejectReason: "", // 驳回理由
});

// 切换视图时的处理函数
const handleViewChange = () => {
  getTableData(); // 切换时重新获取数据
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};

const handleCurrentChange = (val) => {
  page.value = val;
  getTableData();
};

// 查询数据
const getTableData = async () => {
  tableData.value = [];
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    type: viewType.value === "approved" ? 3 : 2, // 根据 viewType 动态设置 type
  };

  const table = await getRequirementList(params);
  if (table.code === 0) {
    tableData.value = table.data.list;
    total.value = table.data.total;
    page.value = table.data.page;
    pageSize.value = table.data.pageSize;
  }
};

getTableData();

// 打开驳回需求弹窗
const openRejectDialog = (row) => {
  rejectForm.value.row = row;
  rejectForm.value.ID = row.ID;
  rejectDialogVisible.value = true;
};

// 关闭驳回需求弹窗
const closeRejectDialog = () => {
  rejectDialogVisible.value = false;
  rejectForm.value.rejectReason = ""; // 清空驳回理由
};

// 提交修改后的驳回理由
const submitReject = async () => {
  ElMessageBox.confirm("确定要驳回吗？以匹配的订单驳回后会删除所有信息！", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await backRequirement({
      order_id: rejectForm.value.ID,
      content: rejectForm.value.rejectReason, // 使用修改后的驳回理由
      user_id: rejectForm.value.row.user_id,
    });
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "修改驳回理由成功",
      });
      getTableData(); // 刷新表格数据
      closeRejectDialog(); // 关闭弹窗
    }
  });
};

// 编辑驳回理由
const editRejectReason = (row) => {
  rejectForm.value.ID = row.ID; // 保存当前订单ID
  rejectForm.value.rejectReason = row.backContent; // 将当前的驳回理由填入输入框
  rejectForm.value.row = row; // 打开弹窗
  rejectDialogVisible.value = true; // 显示驳回理由弹窗
};

const form = ref({
  orderType: "external", // 默认选择外部接单
  technical: "", // 技术方
  price: "", // 价格
  row: {}, // 当前行数据，用于更新
});

const closeDrawer = () => {
  drawerFormVisible.value = false;
  form.value = {
    orderType: "external", // 重置为默认外部接单
    technical: "",
    price: "",
    row: {}, // 清空当前行数据
  };
};

// 通过审核
const approveOrder = (row) => {
  drawerFormVisible.value = true;
  form.value.row = row;
};

// 提交时的逻辑
const enterDrawer = async () => {
  if (form.value.orderType === "internal") {
      // 内部接单请求
	if(parseInt(form.value.price) > parseInt(form.value.row.budgetMax) || parseInt(form.value.price) < parseInt(form.value.row.budgetMin) ){
	   ElMessage({
		  type: "error",
		  message: "成交价格必须在区间内",
		});
		return 
	}
    if(form.value.technical == form.value.row.phone){
	   ElMessage({
		  type: "error",
		  message: "需求发布人和接单人不能是同一个人",
		});
		return 
	}
    const res = await editRequirement({
      type: 1,
      price: parseInt(form.value.price),
      phone: parseInt(form.value.technical),
      order_id: form.value.row.ID,
    });
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "内部接单成功",
      });
    }
  }
  const res = await editRequirement({
    type: 2,
    order_id: form.value.row.ID,
  });
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "内部接单成功",
    });
  }

  closeDrawer();
  getTableData();
};

// 根据 status 返回对应的 type
const getTagType = (status) => {
  switch (status) {
    case 0:
      return "warning";
    case 1:
      return "";
    case 3:
      return "danger";
    case 4:
      return "success";
    default:
      return "primary"; // 或者其他默认类型
  }
};

// 根据 status 返回对应的标签文本
const getTagLabel = (status) => {
  switch (status) {
    case 0:
      return "未提交";
    case 1:
      return "提交未审核";
    case 2:
      return "审核不通过";
    case 3:
      return "审核通过";
    default:
      return "未知";
  }
};
const dialogFormVisible = ref(false);
const currentOrderId = ref(0);
// 处理点击行跳转
const handleRowClick = (row) => {
  currentOrderId.value = row.ID;
  dialogFormVisible.value = true; // 跳转到 OrderDetails 页面，并传递 id
};

const closeDialog = () => {
  dialogFormVisible.value = false;
};
</script>

<style scoped>
.el-radio-group {
  margin-bottom: 20px;
}
.gva-pagination {
  margin: 20px 0;
  text-align: right;
}
.action-buttons {
  display: flex;
  justify-content: center; /* 让按钮在列中居中 */
  gap: 10px; /* 按钮之间的间距 */
}
</style>
